﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.IO;
using SES.CMS.DO;
using SES.CMS.BL;
using System.Web.SessionState;

namespace SES.CMS
{
    public partial class SanPhamChiTiet : System.Web.UI.Page
    {
        ShopingCart vpp = new ShopingCart();
        string sTitle = "";
        private static string sLink = "";
        int ids = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                testtk();

                string CurrentUrl = "http://" + Request.Url.Host + Request.RawUrl;
                hplFacebook.NavigateUrl = hplFacebook.NavigateUrl + CurrentUrl;
                hplGoogle.NavigateUrl = hplGoogle.NavigateUrl + CurrentUrl;
                hplTwitter.NavigateUrl = hplTwitter.NavigateUrl + CurrentUrl;
                
                abc.Attributes.Add("src", "//www.facebook.com/plugins/like.php?href=" + CurrentUrl + "&send=false&layout=button_count&width=450&show_faces=false&action=like&colorscheme=light&font&height=21&appId=379138395463852");
                
                if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
                {
                    //lbloi.Text = "";
                    int id = int.Parse(Request.QueryString["ID"].ToString());
                    ids = id;
                    InitForm(id);
                    MasterPage mt = this.Master as MasterPage;
                    Control uc2 = mt.FindControl("UcDanhMuc2") as Control;
                    uc2.Visible = false;
                    Control uc3 = mt.FindControl("ucMnuSPMoi9") as Control;
                    uc3.Visible = true;
                    string cururl = "http://" + Request.Url.Host + Request.Url.AbsolutePath;
                    fbcm.Attributes.Add("data-href", cururl);
                    //data-href="http://localhost:2396/SanPhamChiTiet/4/But-chi-xin.aspx"

                }
            }
        }

        private void testtk()
        {
            if (Request.Cookies["DaXem"] != null | Convert.ToString(Request.Cookies["DaXem"]) != "")
            {
                HttpCookie ckaccount = Request.Cookies["DaXem"];
                string s = ckaccount["IDSP"].ToString();
                string[] separator = new string[] { "-" };
                string[] kq = s.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                string tem = Request.QueryString["ID"].ToString();
                bool kt = false;
                for (int i = 0; i < kq.Length; i++)
                {
                    if (kq[i].ToString() == tem)
                        kt = true;
                }
                if(kt == false)
                    ckaccount["IDSP"] = s + "-" + Request.QueryString["ID"].ToString();
                ckaccount.Expires.AddMonths(1);
                Response.Cookies.Add(ckaccount);
            }
            else
            {
                HttpCookie ckaccount = new HttpCookie("DaXem");
                ckaccount["IDSP"] = Request.QueryString["ID"].ToString();
                ckaccount.Expires.AddMonths(1);
                Response.Cookies.Add(ckaccount);
            }
        }

        protected void InitForm(int id)
        {
            int sanPhamID = 0;
            DataTable dtSanPham = new cmsSanPhamBL().SelectBySanPhamID(id);
            if (dtSanPham.Rows.Count > 0)
            {
                lblMaSP.Text = dtSanPham.Rows[0]["MaSanPham"].ToString();
                lblTenSP.Text = dtSanPham.Rows[0]["TenSanPham"].ToString();
                sTitle = dtSanPham.Rows[0]["TenSanPham"].ToString();
                Page.Title = sTitle + "- Van phòng phẩm Mỹ Ðình";
                hplLoaiSP.Text = dtSanPham.Rows[0]["LoaiSanPham"].ToString();
                hplLoaiSP.NavigateUrl = "/SanPham/LoaiSP/" + int.Parse(dtSanPham.Rows[0]["LoaiSanPhamID"].ToString()) + "/" + FriendlyUrl(hplLoaiSP.Text);
               

                if (int.Parse(dtSanPham.Rows[0]["NhanHieuID"].ToString()) == 0)
                {
                    lblNhanHieuXuatXu.Text = "Xuất xứ";
                    lblXuatXu.Visible = true;
                    hplNhanHieu.Visible = false;
                    lblXuatXu.Text = dtSanPham.Rows[0]["XuatXu"].ToString();
                }
                if (int.Parse(dtSanPham.Rows[0]["NhanHieuID"].ToString()) != 0)
                {
                    lblNhanHieuXuatXu.Text = "Nhãn hiệu";
                    lblXuatXu.Visible = false;
                    hplNhanHieu.Text = dtSanPham.Rows[0]["NhanHieu"].ToString();
                    hplNhanHieu.NavigateUrl = "/SanPham/NhanHieu/" + int.Parse(dtSanPham.Rows[0]["NhanHieuID"].ToString()) + "/" + FriendlyUrl(hplNhanHieu.Text);
                }
                if (Int64.Parse(dtSanPham.Rows[0]["DonGia"].ToString()) == 0)
                    lblDonGia.Text = "Liên hệ";
                else
                {
                    lblDonGia.Text = string.Format("{0:#,###}", dtSanPham.Rows[0]["DonGia"]) + " VNÐ";
                    if (int.Parse(dtSanPham.Rows[0]["GiamGia"].ToString()) >0)
                        lblGiamGia.Text = string.Format("{0:#,###}", dtSanPham.Rows[0]["GiamGia"]) + " %";
                    else
                        lblGiamGia.Text = "0 %";
                }
                
              //  lblTuKhoa.Text = dtSanPham.Rows[0]["TuKhoa"].ToString();
                lblThongTinChiTiet.Text = dtSanPham.Rows[0]["MoTaChiTiet"].ToString();
                lblBaoHanh.Text = dtSanPham.Rows[0]["BaoHanh"].ToString();
                int iddv = 0;
                string sdfd = dtSanPham.Rows[0]["DonViID"].ToString();
                if(dtSanPham.Rows[0]["DonViID"].ToString()!="")
                    iddv = int.Parse(dtSanPham.Rows[0]["DonViID"].ToString());
                lbDonVi.Text = new cmsDonViBL().Select(new cmsDonViDO { DonViID = iddv }).DonViTinh;

                sLink = "/Media/" + dtSanPham.Rows[0]["HinhAnh"].ToString();
                ln.Text = "<a id='showanh' Title='" + dtSanPham.Rows[0]["LoaiSanPham"].ToString() + "-" + dtSanPham.Rows[0]["TenSanPham"].ToString() + "-" + dtSanPham.Rows[0]["SanPhamID"].ToString() + "' href='/Media/" + dtSanPham.Rows[0]["HinhAnh"].ToString() + "'><img alt='" + dtSanPham.Rows[0]["TenSanPham"].ToString() +"'  src='/Media/" + dtSanPham.Rows[0]["HinhAnh"].ToString() + "' /></a>";
                sanPhamID = int.Parse(dtSanPham.Rows[0]["LoaiSanPhamID"].ToString());
            }
            if (!IsPostBack)
            {
                DataTable dt = new cmsSanPhamBL().SelectByLoaiSanPhamID(sanPhamID);
                DataView dv = new DataView(dt, "SanPhamID<>" + id.ToString(), "SanPhamID DESC", DataViewRowState.CurrentRows);
                if (dv.ToTable().Rows.Count > 0)
                {
                    bindatalist(dt);
                    //rpt.DataSource = dv;
                    //rpt.DataBind();
                }
            }
        }

        protected string FriendlyUrl(string strTitle)
        {
            return Ultility.Change_AV(strTitle);
        }
        public cmsGioHangDO init()
        {
            cmsGioHangDO obj = new cmsGioHangDO();
            if (Session["ClientLoginID"] == null)
                obj.ClientLoginID = 0;
            else
                obj.ClientLoginID = int.Parse(Session["ClientLoginID"].ToString());
            obj.NgayDatHang = Convert.ToDateTime(DateTime.Now.ToString());
            obj.NgayGiaoHang = Convert.ToDateTime(DateTime.Now.ToString());
            obj.SoLuong = 1;
            obj.XuLy = false;
            return obj;
        }
        public string sha()
        {
            string s = sLink;
            return s;
        }
        protected void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string url = Request.Url.AbsolutePath;
            try
            {
                HttpSessionState ss = HttpContext.Current.Session;
                string session = ss.SessionID;
                Int64 id = Int64.Parse(e.CommandArgument.ToString());
                cmsSanPhamDO obj1 = new cmsSanPhamBL().Select(new cmsSanPhamDO { SanPhamID = id });
                float gia = (float)(obj1.DonGia - (obj1.DonGia * obj1.GiamGia) / 100);
                long ClientLoginID = 0;
                if (Session["IDDN"] != null)
                    ClientLoginID = long.Parse(Session["IDDN"].ToString());
                DataTable tb = new DataTable();
                if (Session["GioHang"] != null)
                {
                    vpp.setTable((DataTable)Session["GioHang"]);
                    tb = vpp.getTable();
                    bool kt = false;
                    foreach (DataRow dr in tb.Rows)
                    {
                        if (Int64.Parse(dr[1].ToString()) == id)
                            kt = true;
                    }
                    if (kt == true)
                        tb = vpp.upDate(tb, id, 1, gia);
                    else
                        tb = vpp.addSP(id, 1, gia);
                    Session["GioHang"] = tb;
                }
                else
                {
                    tb = vpp.init(id, 1, gia);
                    Session["GioHang"] = tb;
                }

                Ultility.Alert("Đặt mua thành công!" + tb.Rows.Count, url);
            }
            catch
            {
                Ultility.Alert("Lỗi!", url);
            }
        }

        protected void lbtnAddToCart_Click(object sender, ImageClickEventArgs e)
        {
            string url = Request.Url.AbsolutePath;
            try
            {
                HttpSessionState ss = HttpContext.Current.Session;
                string session = ss.SessionID;
                Int64 id = Int64.Parse(Request.QueryString["ID"].ToString());
                cmsSanPhamDO obj1 = new cmsSanPhamBL().Select(new cmsSanPhamDO { SanPhamID = id });
                float gia = (float)(obj1.DonGia - (obj1.DonGia * obj1.GiamGia) / 100);
                long ClientLoginID = 0;
                if (Session["IDDN"] != null)
                     ClientLoginID = long.Parse(Session["IDDN"].ToString());
                DataTable tb = new DataTable();
                if (Session["GioHang"] != null)
                {
                    vpp.setTable((DataTable)Session["GioHang"]);
                    tb = vpp.getTable();
                    bool kt = false;
                    foreach (DataRow dr in tb.Rows)
                    {
                        if (Int64.Parse(dr[1].ToString()) == id)
                            kt = true;
                    }
                    if (kt == true)
                        tb = vpp.upDate(tb,id, 1, gia);
                    else
                        tb = vpp.addSP(id,1, gia);
                    Session["GioHang"] = tb;
                }
                else
                {
                    tb = vpp.init(id,  1, gia);
                    Session["GioHang"] = tb;
                }
                
                Ultility.Alert("Đặt mua thành công!" + tb.Rows.Count, url);
            }
            catch
            {
                Ultility.Alert("Lỗi!", url);
            }
        }

        public int CurrentPage
        {
            get
            {
                // look for current page in ViewState
                object o = this.ViewState["_CurrentPage"];
                if (o == null)
                    return 0;	// default to showing the first page
                else
                    return (int)o;
            }

            set
            {
                this.ViewState["_CurrentPage"] = value;
            }
        }
        private void bindatalist(DataTable dt)
        {
            rpt.Dispose();
            PagedDataSource objPds = new PagedDataSource();
            objPds.DataSource = dt.DefaultView;
            objPds.AllowPaging = true;
            objPds.PageSize = 15;
            objPds.CurrentPageIndex = CurrentPage;
            cmdPrev.Visible = !objPds.IsFirstPage;
            cmdNext.Visible = !objPds.IsLastPage;
            if (dt.Rows.Count > 0)
            {
                rpt.Visible = true;
                rpt.DataSource = objPds;
                rpt.DataBind();
            }
            else
            {
                //lbThongbao.Visible = true;
                //lbThongbao.Text = "Không có sản phẩm!";
            }
        }
        protected void cmdPrev_Click(object sender, ImageClickEventArgs e)
        {
            CurrentPage -= 1;

            // Reload control
            InitForm(ids);
        }
        protected void cmdNext_Click(object sender, ImageClickEventArgs e)
        {
            CurrentPage += 1;
            InitForm(ids);
        }
    }
}
